<template>
  <div class="movie-ticket-system">
    <h3 class="section-title">热门电影票</h3>

    <!-- 电影票列表 - 横向排列 -->
    <div v-if="tickets.length > 0" class="ticket-list">
      <div v-for="ticket in tickets" :key="ticket.id" class="ticket-item">
        <img
            :src="ticket.poster"
            class="ticket-poster"
            alt="电影海报"
            @error="onImageError"
        />
        <div class="ticket-details">
          <div class="ticket-title">{{ ticket.title }}</div>
          <div class="ticket-info">{{ ticket.duration }}分钟 | {{ ticket.genre }}</div>
          <div class="ticket-cinema">{{ ticket.cinema }}</div>
          <div class="ticket-time">
            {{ formatDate(ticket.date) }} {{ formatTime(ticket.time) }}
          </div>
        </div>
        <div class="ticket-price-info">
          <div class="original-price">¥{{ ticket.price }}</div>
          <div v-if="ticket.discount" class="discount-price">
            券后价: ¥{{ (ticket.price - ticket.discount).toFixed(2) }}
          </div>
        </div>
        <el-button
            type="primary"
            size="small"
            @click="showBuyDialog(ticket)"
            :loading="buyLoading[ticket.id]"
        >
          {{ buyLoading[ticket.id] ? '购买中...' : '立即购票' }}
        </el-button>
      </div>
    </div>

    <!-- 空状态提示 -->
    <div v-else class="empty-state">
      <el-icon><CircleCloseFilled /></el-icon>
      <p>暂无电影票信息</p>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
      />
    </div>

    <!-- 购买确认对话框 -->
    <el-dialog
        v-model="buyDialogVisible"
        title="确认购买"
        width="30%"
        center
        :before-close="handleDialogClose"
    >
      <div class="dialog-content">
        <p>你确定要购买《{{ selectedTicket.title }}》电影票吗？</p>
        <p>放映时间: {{ formatDate(selectedTicket.date) }} {{ formatTime(selectedTicket.time) }}</p>
        <p>放映影院: {{ selectedTicket.cinema }}</p>
        <p class="price-info">
          原价: <span class="original-price">¥{{ selectedTicket.price }}</span>
          <span v-if="selectedTicket.discount"> 立减: ¥{{ selectedTicket.discount }}</span>
          <span class="final-price"> 实付: ¥{{ (selectedTicket.price - (selectedTicket.discount || 0)).toFixed(2) }}</span>
        </p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="confirmBuyTicket">确认购买</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { CircleCloseFilled } from '@element-plus/icons-vue'
import movieService from '@/services/movie'

// 状态管理
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const tickets = ref([])
const buyDialogVisible = ref(false)
const buyLoading = ref({}) // 记录每个电影票的购买加载状态
const selectedTicket = ref({
  id: null,
  title: '',
  date: '',
  time: '',
  cinema: '',
  price: 0,
  discount: 0
})

// 图片加载失败处理
const onImageError = (e) => {
  e.target.src = 'https://picsum.photos/400/200?random=' + Math.random()
}

// 格式化日期和时间
const formatDate = (dateString) => {
  if (!dateString) return ''
  return dateString // 后端返回的日期已经是 YYYY-MM-DD 格式
}

const formatTime = (timeString) => {
  if (!timeString) return ''
  // 提取时间部分，忽略毫秒
  return timeString.split('.')[0].substring(0, 5) // 只取前5位 (HH:mm)
}

// 获取电影票列表
const fetchTickets = () => {
  movieService.getTickets(currentPage.value, pageSize.value)
      .then(response => {
        // 解析后端数据结构: response.data.list
        if (response.data && response.data.list) {
          tickets.value = response.data.list
          total.value = response.data.total
          console.log('成功获取电影票数据:', tickets.value)
        } else {
          console.error('API返回数据结构异常:', response.data)
          tickets.value = []
          total.value = 0
        }
      })
      .catch(error => {
        console.error('获取电影票失败:', error)
        ElMessage.error('获取电影票失败，请稍后再试')
        tickets.value = []
        total.value = 0
      })
}
// 分页大小变更处理
const handlePageSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  fetchTickets()
}

// 页码变更处理
const handleCurrentPageChange = (newPage) => {
  currentPage.value = newPage
  fetchTickets()
}

// 显示购买对话框
const showBuyDialog = (ticket) => {
  selectedTicket.value = { ...ticket } // 创建副本
  buyDialogVisible.value = true
}

// 关闭购买对话框
const handleDialogClose = () => {
  buyDialogVisible.value = false
}

// 确认购买
const confirmBuyTicket = () => {
  if (!selectedTicket.value || !selectedTicket.value.id) return

  // 设置加载状态
  buyLoading.value[selectedTicket.value.id] = true

  // 调用后端购买接口
  movieService.buyTicket(selectedTicket.value.id)
      .then(response => {
        ElMessage.success('购买成功！请前往订单页面查看')
      })
      .catch(error => {
        console.error('购买失败:', error)
        ElMessage.error(error.response?.data?.message || '购买失败，请稍后再试')
      })
      .finally(() => {
        // 无论成功失败，都取消加载状态
        buyLoading.value[selectedTicket.value.id] = false
        buyDialogVisible.value = false
      })
}

// 组件挂载时获取数据
onMounted(fetchTickets)
</script>

<style scoped>
.movie-ticket-system {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.section-title {
  margin-top: 0;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
  color: #303133;
  font-size: 20px;
  font-weight: 500;
}

/* 电影票列表横向排列布局 */
.ticket-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  justify-content: center;
}

.ticket-item {
  display: flex;
  flex-direction: column;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  min-height: 420px; /* 确保卡片有足够高度 */
}

.ticket-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.12);
}

.ticket-poster {
  width: 100%;
  height: 180px;
  margin-bottom: 15px;
  border-radius: 4px;
  object-fit: cover;
  border: none;
  background-color: #f5f7fa; /* 占位背景色 */
}

.ticket-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 10px;
}

.ticket-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.ticket-info, .ticket-cinema {
  color: #606266;
  font-size: 13px;
  margin: 0;
}

.ticket-time {
  font-weight: 500;
  color: #e54847;
  font-size: 14px;
  margin-top: auto;
}

.ticket-price-info {
  margin: 10px 0;
  text-align: center;
}

.original-price {
  font-size: 18px;
  font-weight: bold;
  color: #e54847;
  text-decoration: line-through;
  margin-bottom: 5px;
  display: block;
}

.discount-price {
  font-size: 22px;
  font-weight: bold;
  color: #e54847;
}

/* 购买按钮样式调整 */
.el-button {
  width: 100%;
  margin-top: 10px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #909399;
  margin-top: 30px;
}

.empty-state i {
  font-size: 80px;
  margin-bottom: 20px;
  color: #dcdfe6;
}

.pagination-container {
  margin-top: 40px;
  display: flex;
  justify-content: center;
}

.dialog-content {
  text-align: center;
  padding: 20px 0;
}

.dialog-content p {
  margin: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.final-price {
  font-weight: bold;
  color: #e54847;
}
</style>